(async function () {
  
  let spinesDataFath = chrome.runtime.getURL('../config/spinesData.json')
  var xhr = new XMLHttpRequest()
  xhr.open("GET", spinesDataFath, true)
  xhr.send()
  const getSpinesData = () => {
    return new Promise((resolve, reject) => {
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          resolve(xhr.responseText)
        }
      }
    })
  }
  let popupSpineList
  await getSpinesData().then(async (res) => {
    popupSpineList = JSON.parse(res).popupSpineList
  })
  

  Ospine.injectOption(popupSpineList)
  Ospine.init()
  
  let spineCharSelectPopup = document.getElementById('spine-char-select-popup')
  let spineCharSelectInput = document.getElementById('spine-char-select-input')
  let ospSelectDirectionPopup = document.getElementById('osp-select-direction-popup')
  let ospSelectDirectionInput = document.getElementById('osp-select-direction-input')
  
  for (const item of popupSpineList) {
    let spineCharSelectOption = document.createElement('div')
    spineCharSelectOption.setAttribute('class', 'spine-char-select-option')
    spineCharSelectOption.innerHTML = `<p>${item.name}</p>`
    spineCharSelectOption.onclick = () => {
      spineCharSelectInput.value = item.name
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        // 传过去的参数有字节限定，这里只能传个key
        chrome.tabs.sendMessage(tabs[0].id, { action: "selectSpine", spine: item.key }, function (response) {

        })
      })
    }
    spineCharSelectPopup.appendChild(spineCharSelectOption)
  }
  let directionData = [{text: '朝左', id: 0},{text: '朝右', id: 1}]
  for (const item of directionData) {
    let spineCharSelectOption = document.createElement('div')
    spineCharSelectOption.setAttribute('class', 'spine-char-select-option')
    spineCharSelectOption.innerHTML = `<p>${item.text}</p>`
    spineCharSelectOption.onclick = () => {
      ospSelectDirectionInput.value = item.text

      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        // 传过去的参数有字节限定，这里只能传个key
        chrome.tabs.sendMessage(tabs[0].id, { action: "changeDirection", direction: item.id }, function (response) {

        })
      })
    }
    ospSelectDirectionPopup.appendChild(spineCharSelectOption)
  }
  // spineCharSelectPopup.onmouseover = () => {
  //   document.getElementById('request-msg').innerText = window.getComputedStyle(spineCharSelect).pointerEvents
  //   spineCharSelect.style.pointerEvents = 'none'
  // }
  const openSpineEl = document.getElementById('open-spine')
  const openMovelineEl = document.getElementById('open-moveline')
  const settingPositionEl = document.getElementById('setting-position')
  const settingScale = document.getElementById('setting-scale')
  const defaultSetting = document.getElementById('default-setting')
  const charLoad = document.getElementById('char-load')

  // 获取小人状态和基本信息
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, { action: "getSpineState" }, function (response) {
      if (!response.code || response.code != 200) {
        return
      }
      switch (response.data.state) {
        case 'block':
          openSpineEl.checked = true
          let indexSpine = popupSpineList.find(p => p.key === response.data.spine)
          spineCharSelectInput.value = indexSpine.name
          ospSelectDirectionInput.value = directionData.find(p => p.id == (response.data.direction==1?1:0))?.text
          settingScale.value = response.data.scale*100
          const leftSize = (settingScale.value - settingScale.min)/(settingScale.max - settingScale.min)*100
          settingScale.style.backgroundSize = `${leftSize}% 100%`
          break
        case 'none':
          openSpineEl.checked = false
        default:
          break
      }
      if (response.data.positionState === 'none') {
        openMovelineEl.checked = false
      }
      else {
        openMovelineEl.checked = true
      }
    })
  })

  // 开关小人状态
  openSpineEl.onchange = () => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { action: "changeSpineState" }, function (response) {
      })
    })
  }

  // 开启动线
  openMovelineEl.onchange = () => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { action: "changePositionLine" }, function (response) {
      })
    })
  }

  // 设定位置
  // settingPositionEl.onclick = () => {
  //   if (!openMovelineEl.checked) {
  //     openMovelineEl.checked = true
  //     chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  //       chrome.tabs.sendMessage(tabs[0].id, { action: "changePositionLine" }, function (response) {
  //       })
  //     })
  //   }
  //   chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  //     chrome.tabs.sendMessage(tabs[0].id, { action: "settingPosition" }, function (response) {
  //     })
  //   })
  // }
  // 修改大小
  settingScale.oninput = () =>  {
    const leftSize = (settingScale.value - settingScale.min)/(settingScale.max - settingScale.min)*100
    settingScale.style.backgroundSize = `${leftSize}% 100%`
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { action: "changeScale", value: settingScale.value}, function (response) {
      })
    })
  }

  // 提交表单
  settingScale.onchange = () =>  {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { action: "submitScale", value: settingScale.value}, function (response) {
      })
    })
  }

  // 恢复默认设置
  defaultSetting.onclick = () => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { action: "defaultSetting" }, function (response) {
      })
    })
  }
  // 测试在本地文件中读取人物
  charLoad.onclick = () => {
    // document.getElementById('request-msg').innerText = JSON.stringify(charLoad.value) 
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { action: "loadchar" }, function (response) {
      })
    })
  }
  // charLoad.onselect = () => {
  //   charLoad.value
  // }
  // charLoad
  // 测试代码
  // document.getElementById('request-msg').innerText = '1111'
})()
